package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.RecommendUser;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.RecommendUserApi;
import com.tanhua.dubbo.server.vo.PageResult;
import com.tanhua.dubbo.server.vo.RecommendUserQueryParam;
import com.tanhua.dubbo.server.vo.TodayBest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: RecommendUserService
 * @Author:王晨晗
 * @Description: 用户推荐业务层,获取推荐用户
 * @Date: 2021/12/28/18:43
 */
@Service
public class RecommendUserService {

    @Reference
    public RecommendUserApi recommendUserApi;  //dubbo服务

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;       //默认推荐用户

    @Autowired
    public UserInfoMapper userInfoMapper;
    /**
     * @description 根据用户的id 查询对应的佳人信息
     * @param id : 此id对应recommend_user表中的toUserId,即当前登录用户
     * @updateTime 2021/12/28 18:46
     * @return: com.tanhua.common.vo.TodayBest
     */
    public TodayBest findTodayBest(Long id) {
        //调用dubbo服务,查询今日佳人的信息
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(id);
        //判断是否查询到数据,如没有,推荐默认佳人
        if (recommendUser == null){
            //推荐默认佳人
            recommendUser = new RecommendUser();
            recommendUser.setUserId(defaultUser);
            recommendUser.setScore(88D);
        }
        //调用获取佳人具体信息的方法, 封装到实体类中
        TodayBest todayBest = getTodayBest(recommendUser);
        //返回结果
        return todayBest;
    }


    /**
     * @description 根据条件 获取推荐列表
     * @param id  此id对应recommend_user表中的toUserId,即当前登录用户
     * @param params  查询条件
     * @updateTime 2021/12/28 20:25
     * @return: java.util.List<com.tanhua.common.vo.TodayBest>
     */
    public PageResult queryRecommendation(Long id, RecommendUserQueryParam params) {
        //定义查询条件,查询mysql数据库
        LambdaQueryWrapper<UserInfo> query = new LambdaQueryWrapper<>();
        //查询条件如下
        query.eq(UserInfo::getSex, StringUtils.equalsIgnoreCase(params.getGender() , "man") ? 1 : 2);
        query.ge(UserInfo::getAge , params.getAge());
        query.like(UserInfo::getCity , params.getCity());
        query.eq(UserInfo::getEdu , params.getEducation()).select(UserInfo::getUserId);   //仅需要符合条件的用户id
        //进行数据库查询,获取符合条件的数据集合
        List<UserInfo> userInfos = userInfoMapper.selectList(query);

        //将查询出来的id存放到数组中
        List<Object> userIds = CollUtil.getFieldValues(userInfos, "userId");
        /*Long[] userIds = new Long[userInfos.size()];
        for (int i = 0; i < userInfos.size(); i++) {
            userIds[i] = userInfos.get(i).getUserId();
        }*/

        //调用查询推荐用户数据表的查询方法,将条件传递 , 得到用户推荐列表
        List<RecommendUser> recommendUserList = recommendUserApi.queryRecommendation(id , userIds , params.getPage() , params.getPagesize());

        //遍历查询出的列表信息,得到userid , 查询UserInfo具体信息,封装到TodayBest实体类中,存入集合
        List<TodayBest> todayBestList=new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            //调用获取佳人具体信息的方法, 封装到实体类中
            TodayBest todayBest = getTodayBest(recommendUser);
            todayBestList.add(todayBest);
        }

        //将信息封装到前端响应实体类中
        PageResult result = new PageResult();
        if (recommendUserList.size() > 0){
            result.setPage(params.getPage());               //当前页
            result.setPagesize(params.getPagesize());       //每页条数
            result.setItems(todayBestList);                 //数据列表
            //获取总条数,总页数
            Integer count = Math.toIntExact(recommendUserList.get(0).getToUserId());               //总条数
            //总页数
            Integer pages = count % params.getPagesize() == 0 ? count / params.getPagesize() : count / params.getPagesize() + 1;
            result.setPages(pages);             //总页数
            result.setCounts(count);            //总条数
        }else{
            result.setPage(params.getPage()-1);               //当前页
            result.setPagesize(params.getPagesize());       //每页条数
        }
        //返回条件
        return result;
    }

    /**
     * @description 根据条件 获取推荐列表
     * @param id  此id对应recommend_user表中的toUserId,即当前登录用户
     * @param params  查询条件
     * @updateTime 2021/12/28 20:25
     * @return: java.util.List<com.tanhua.common.vo.TodayBest>
     */
    public PageResult queryRecommendation1(Long id, RecommendUserQueryParam params) {
        //调用查询推荐用户数据表的查询方法,将条件传递 , 得到用户推荐列表
        List<RecommendUser> recommendUserList = recommendUserApi.queryRecommendation1(id , params.getPage() , params.getPagesize());

        //遍历查询出的列表信息,得到userid , 查询UserInfo具体信息,封装到TodayBest实体类中,存入集合
        List<TodayBest> todayBestList=new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            //调用获取佳人具体信息的方法, 封装到实体类中
            TodayBest todayBest = getTodayBest(recommendUser);
            todayBestList.add(todayBest);
        }

        //将信息封装到前端响应实体类中
        PageResult result = new PageResult();
        if (recommendUserList.size() > 0){
            result.setPage(params.getPage());               //当前页
            result.setPagesize(params.getPagesize());       //每页条数
            result.setItems(todayBestList);                 //数据列表
            //获取总条数,总页数
            Integer count = Math.toIntExact(recommendUserList.get(0).getToUserId());               //总条数
            //总页数
            Integer pages = count % params.getPagesize() == 0 ? count / params.getPagesize() : count / params.getPagesize() + 1;
            result.setPages(pages);             //总页数
            result.setCounts(count);            //总条数
        }else{
            result.setPage(params.getPage()-1);               //当前页
            result.setPagesize(params.getPagesize());       //每页条数
        }
        //返回条件
        return result;
    }


    /**
     * @description  根据RecommendUser信息,获取用户详细信息封装todayBest
     * @param recommendUser
     * @updateTime 2021/12/29 9:03
     * @return: com.tanhua.common.vo.TodayBest
     */
    public TodayBest getTodayBest(RecommendUser recommendUser){
        TodayBest todayBest = new TodayBest();
        todayBest.setId(recommendUser.getUserId());         //设置用户id
        //转换缘分值
        double score = Math.floor(recommendUser.getScore());
        todayBest.setFateValue(Double.valueOf(score).longValue());      //缘分值

        //根据佳人的id查询其详细信息进行封装
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserId , todayBest.getId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        //封装剩余信息
        todayBest.setAvatar(userInfo.getLogo());        //图片信息
        todayBest.setNickname(userInfo.getNickName());  //昵称
        todayBest.setAge(userInfo.getAge());            //年龄
        todayBest.setTags(userInfo.getTags().split(",")); //标签
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");   //性别

        return todayBest;
    }

    /**
     * @description 查询用户之间的缘分值
     * @param userId
     * @param toUserId
     * @return
     */
    public Double queryScore(Long userId, Long toUserId){
        Double score = recommendUserApi.queryScore(userId, toUserId);
        if(ObjectUtil.isNotEmpty(score)){
            return score;
        }
        //默认值
        return 98d;
    }

    /**
     * @description 查询探花卡片列表
     * @param id
     * @param count
     * @return
     */
    public List<RecommendUser> queryCardList(Long id, int count) {
        return recommendUserApi.queryCardList(id , count);
    }
}
